package handler

import (
	"context"
	"encoding/json"
	"errors"
	pb "mpps/services/srv-ProgramRollback/proto"
	common "mpps/tools/common"
	"mpps/tools/repository/dao"
	"mpps/tools/repository/dao/program"
)

type ProgramRollback struct {
}

func NewProgramRollback() *ProgramRollback {
	return &ProgramRollback{}
}

// Call is a single request handler called via client.Call or the generated client code
func (c *ProgramRollback) Call(ctx context.Context, req *pb.Request, rsp *pb.Response) error {
	if len(req.Mode) <= 0 || len(req.FileType) <= 0 {
		return errors.New(common.ErrParamsValidation.Message)
	}
	if req.FileType != program.Js.String() && req.FileType != program.Program.String() {
		return errors.New(common.ErrParamsValidation.Message)
	}
	if req.Mode != program.Dev.String() && req.Mode != program.Preview.String() && req.Mode != program.Prod.String() {
		return errors.New(common.ErrParamsValidation.Message)
	}
	if req.FileType == program.Program.String() && len(req.ProgramId) <= 0 {
		return errors.New(common.ErrParamsValidation.Message)
	}
	query := program.MiniProgram{}
	where := program.MiniProgram{}
	rb, _ := json.Marshal(req)
	json.Unmarshal(rb, &where)
	result := dao.GetDB(ctx).
		Model(&program.MiniProgram{}).
		Where(where).
		Order("created_at desc").
		Limit(1).
		Find(&query)
	if result.RowsAffected > 0 {
		// 这里的delete实际是SET deleted_at
		result = dao.GetDB(ctx).
			Model(&program.MiniProgram{}).
			Where("id = ?", query.ID).
			Delete(&query)
		if result.RowsAffected > 0 {
			rsp.Code = int32(common.OK.Code)
			rsp.Msg = common.OK.Message
		}
	} else {
		return errors.New(common.ErrPostRollback.Message)
	}
	return nil
}
